<template>
  <div class="select-product">
    <!--商品分类 -->
    <div class="product-category">
      <el-button
        v-for="(item, index) in categoryDataList"
        :key="index"
        :text="currentTabIndex === index ? false : true"
        :bg="currentTabIndex === index ? false : true"
        :type="currentTabIndex === index ? 'success' : ''"
        @click="selectProduct(index, item._id)"
        >{{ item.categoryName }}</el-button
      >
    </div>
    <!--商品数据 -->
    <div class="product-data-list">
      <div
        class="product-data-item"
        v-for="(item, index) in productDataList"
        :key="index"
        @click="proceedToOrder(item)"
      >
        <div class="product-image">
          <el-image :src="item.goods_image" fit="cover" :lazy="true"></el-image>
          <span class="disable-order" v-if="item.delist || item.total_stock <= 0">
            {{ item.delist && item.total_stock <= 0 ? "已下架" : "已售完" }}
          </span>
        </div>
        <span class="product-name overflow-text">{{ item.goods_name }}</span>
        <span>¥{{ item.display_price }}</span>
      </div>
    </div>
    <!--分页 -->
    <el-pagination
      class="pager-next"
      background
      layout="prev, pager, next"
      :total="totalQuantity"
      :default-page-size="15"
      hide-on-single-page
      :current-page="page"
      @current-change="currentChange"
    >
    </el-pagination>
  </div>
  <!-- 由规格的商品弹窗 -->
  <el-dialog
    v-model="productSpecModal"
    title="选择规格"
    width="400"
    :close-on-click-modal="false"
    v-for="(item, index) in productSpecModalData"
    :key="index"
  >
    <el-image
      :src="item.goods_image"
      fit="cover"
      :lazy="true"
      class="product-spec-image"
    ></el-image>
    <span class="product-spec-name">{{ item.goods_name }}</span>
    <div class="select-spec">
      <el-button
        v-for="(item_a, index_a) in item.goods_stats"
        :key="index_a"
        :disabled="item_a.productStock <= 0 ? true : false"
        :type="buttonTypeIndex === index_a ? 'success' : ''"
        @click="
          selectProductAttr(index_a, item_a.productPrice, item_a.productAttributes, item_a._id)
        "
        >{{ item_a.productAttributes }}</el-button
      >
    </div>
    <span class="select-total-price">合计：¥{{ productAttrPrice }}</span>
    <el-button type="success" class="add-to-cart" @click="orderMultiVariant(item)">加购</el-button>
  </el-dialog>
</template>


<script setup lang="ts">
import { ref, onMounted } from "vue";
import { orderForCategoryApi, orderForProductApi } from "@/api/api";
import type { allcateGoryType, getGoodsRes } from "@/types/index";
//#region
// 请求商品分类和商品数据
onMounted(async () => {
  const categoryData = await orderForCategoryApi();
  categoryDataList.value = categoryData.data;
  // 存储默认的商品分类id
  categoryid.value = categoryData.data[0]._id;
  const productData = await orderForProductApi();
  productDataList.value = productData.data.res;
  totalQuantity.value = productData.data.total;
});
// 存储商品分类数据
const categoryDataList = ref<allcateGoryType[]>([]);
// 存储商品数据
const productDataList = ref<getGoodsRes[]>([]);
// 存储商品总条数
const totalQuantity = ref(0);
// 存储分类id
const categoryid = ref("");
// 存储当前页数
const page = ref(1);
// 分页时触发
function currentChange(value: number) {
  page.value = value;
  searchForProduct(categoryid.value, page.value);
}
// 存储选中的分类按钮下标
const currentTabIndex = ref(0);
// 选择商品分类时触发
function selectProduct(index: number, id: string) {
  currentTabIndex.value = index;
  categoryid.value = id;
  page.value = 1;
  searchForProduct(categoryid.value, page.value);
}
// 筛选商品
async function searchForProduct(categoryid: string, page: string | number) {
  const productData = await orderForProductApi({ categoryid, page });
  productDataList.value = productData.data.res;
  totalQuantity.value = productData.data.total;
}
//#endregion

// 选择商品加入购物车
function proceedToOrder(params: getGoodsRes) {
  // 如果已售完或已下架
  if (params.delist || params.total_stock <= 0) return false;
  // 判断是不是有规格的商品
  if (params.hasSpecs) {
    productSpecModalData.value = [params];
    // 弹出规格弹窗默认选在第一个属性上
    productAttrPrice.value = params.goods_stats[0].productPrice;
    attributeVal.value = params.goods_stats[0].productAttributes;
    attributeIdVal.value = params.goods_stats[0]._id;
    buttonTypeIndex.value = 0;
    productSpecModal.value = true;
    return false;
  }
  // 没有规格的下单
  publicData(params, "", params.goods_stats[0]._id, params.display_price);
}
// 属性名称
const attributeVal = ref("");
// 属性id
const attributeIdVal = ref("");
// 选择属性
function selectProductAttr(index: number, price: number, attribute: string, attributeId: string) {
  buttonTypeIndex.value = index;
  productAttrPrice.value = price;
  attributeVal.value = attribute;
  attributeIdVal.value = attributeId;
}
// 有规格的商品加入购物车
function orderMultiVariant(params: getGoodsRes) {
  publicData(params, attributeVal.value, attributeIdVal.value, productAttrPrice.value);
  productSpecModal.value = false;
}

// 存储有规格的商品弹窗里的数据
const productSpecModalData = ref<getGoodsRes[]>([]);
// 存储有规格的商品弹窗里的价格
const productAttrPrice = ref(0);
// 存储按钮选中状态：默认选在第一个上：有规格的商品弹窗里
const buttonTypeIndex = ref(0);
// 弹窗显示或者隐藏
const productSpecModal = ref(false);

// 提交到购物车
import { pendingOrders } from "@/store/index";
function publicData(
  params: getGoodsRes,
  attribute: string,
  attributeId: string,
  display_price: number
) {
  pendingOrders().addToorder({
    goods_id: params._id,
    category_id: params.category_id,
    goods_image: params.goods_image,
    goods_name: params.goods_name,
    quantity: 1,
    display_price,
    goods_describe: params.goods_describe,
    attribute,
    attributeId,
    totalPrice: 0,
  });
}
</script>
<style scoped>
.select-product {
  flex: 1;
  margin-left: 10px;
}
.product-category >>> .el-button {
  margin-right: 12px;
  margin-bottom: 12px;
  border: none;
}
/* .product-data-height {
  height: 655px;
  overflow-y: auto;
} */
.product-data-list {
  display: grid;
  grid-template-columns: repeat(6, 1fr); /* 创建6列，每列等宽 */
  gap: 20px; /* 定义网格线之间的间距 */
}
.product-image >>> .el-image {
  width: 100%;
  height: 110px;
  border-radius: 4px;
}
.product-image {
  height: 110px;
  position: relative;
}
.disable-order {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  text-align: center;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 5px 0;
}
.product-data-item {
  display: flex;
  flex-direction: column;
  cursor: pointer;
}
.product-name {
  margin: 5px 0;
}
.product-spec-image {
  width: 100%;
  height: 200px;
}
.select-spec {
  padding: 10px 0 30px 0;
}
.product-spec-name {
  padding: 10px 0;
  font-weight: bold;
  display: block;
}
.select-spec >>> .el-button {
  margin-right: 12px;
  margin-bottom: 12px;
}
.select-total-price {
  display: block;
  font-weight: bold;
}
.add-to-cart {
  width: 100%;
  margin-top: 20px;
  padding: 17px 0;
}
.el-button + .el-button {
  margin-left: 0 !important;
}
</style>
